﻿using System;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Mr.Wang.JsonExp
{
    public static class JsonExp
    {

        /// <summary>
        /// 拓展方法匹配json中的value
        /// </summary>
        /// <param name="jsonStr">json串</param>
        /// <param name="key">扁平化key[例如 "data:0:parkName" ]</param>
        /// <returns></returns>
        public static string MatchValueByNewtonSoft(this string jsonStr, string key)
        {
            try
            {
                JObject objJson = JObject.Parse(jsonStr);
                if (!key.Contains(":") || string.IsNullOrEmpty(key))
                {
                    return null;
                }
                string[] keyArr = key.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);

                JToken resultObj = objJson;
                for (int i = 0; i < keyArr.Length; i++)
                {
                    if (i % 2 != 0 && int.TryParse(keyArr[i], out int keyInt))
                    {
                        resultObj = resultObj[keyInt];
                    }
                    else
                    {
                        resultObj = resultObj[keyArr[i]];
                    }

                }
                return resultObj.ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }

        }

        /// <summary>
        /// 拓展方法匹配json中的value[正则表达式实现]
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <param name="keyName">目标key</param>
        /// <returns></returns>
        public static string MatchValueByRegex(this string jsonStr, string keyName)
        {
            string regexPattera = $@"""{keyName}""\s*:\s*”*(.*)“*?\s*,*";
            Match resultMatch = Regex.Match(jsonStr, regexPattera);
            if (!resultMatch.Success)
            {
                return null;
            }
            string resultVal = resultMatch.Groups[1].Value;
            return resultVal.Trim().Trim(',').Trim('"');
        }
    }
}
